package dao.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import dao.IProjectDao;
import entity.Project;

public class ProjectDaoImpl implements IProjectDao{

	// 1.创建一个保存项目的集合
	public List<Project> projectList;
	
	public ProjectDaoImpl() {
		// 2.初始化集合, 否则NPE
		this.projectList = new ArrayList<>();
	}

	@Override
	public boolean insert(Project project) {
		// 先判断projectList是否有相同id的项目
		// contains底层调用每个元素和参数比较equals
		if (!projectList.contains(project)) {
			return projectList.add(project);
		}else {
			return false;
		}
	}

	@Override
	public boolean update(Project project) {
		// 集合中寻找要被更新的id的项目
		int index = projectList.indexOf(project);
		if (index == -1) {
			return false;
		}else {
			projectList.set(index, project);
			return true;
		}
	}

	@Override
	public boolean delete(int id) {
		// 遍历所有项目，判断是否有要删除的id
		for(Project p : projectList) {
			if (p.getId() == id) {
				return projectList.remove(p);
			}
		}
		return false;
	}

	@Override
	public Project selectById(int id) {
		
		for(Project p : projectList) {
			if (p.getId() == id) {
				return p;
			}
		}
		return null;
	}

	@Override
	public List<Project> selectByTL(String tl) {
		return projectList.stream()
				   .filter(p -> p.getTeamLeader().equals(tl))
				   .collect(Collectors.toList());
	}

	@Override
	public List<Project> selectByLanguage(String language) {
		return projectList.stream()
				   .filter(p -> p.getLanguage().equals(language))
				   .collect(Collectors.toList());
	}

	@Override
	public List<Project> selectByOnLine(boolean status) {
		return projectList.stream()
				   .filter(p -> p.isOnLine() == status)
				   .collect(Collectors.toList());
	}
}
